import java.util.concurrent.*;

/**
 * <pre>
 * Created with IntelliJ IDEA.
 * User: zhengzhi
 * Date: 2017/9/6
 * Time: 11:33
 * To change this template use File | Settings | File Templates.
 * </pre>
 *
 * @author Administrator
 */

//使用callable + Future获取执行结果
public class FutureTest {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();

        Future<Integer> result = executor.submit(task);
        executor.shutdown();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果"+result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }

}


//构造一个线程 用于执行1到1000的加法
class Task implements Callable<Integer>{
    public Integer call() throws Exception {
        System.out.println("执行子线程，进行计算");
        Thread.sleep(3000);

        int sum = 0;
        for(int i = 0;i<1000;i++){
            sum += i;
        }

        return sum;
    }
}